/*jslint vars: true, forin:true, sloppy: true*/
/*global angular, probe*/
probe.controller("assert", function ($scope, $element, $filter,
        ocDialog, Capture, GET_FRAME) {
	var DI = ocDialog.queryDI($element);
	var data = DI.share;
	//default
	$scope.exp = 'textarea';
	$scope.timeout = 3000;
	$scope.key = 'key_' + /[0-9]{5,11}/.gen;//we can use randexp
	if (data.edit) {
		$scope.exp = data.ins[data.index].BODY.exp;
		$scope.timeout = data.ins[data.index].BODY.timeout;
		$scope.key = data.ins[data.index].BODY.key;
	}

	$scope.capture = function () {
		GET_FRAME().style.backgroundColor = '#ffffff';
		Capture.setZIndex(550).setContext(GET_FRAME().contentWindow);
		//remove the block on parent to fix a bug on IE
		DI.$$parent.setBlock();
		//hide it temporarily
		DI.$$element.css({
			"opacity": 0
		});

		Capture.watchHTML(function (selector) {
			GET_FRAME().style.zIndex = 0;
			GET_FRAME().style.backgroundColor = '';
			DI.$$element.css({
				"opacity": 1
			});
			//reinstall the block
			DI.$$parent.setBlock(true);
			$scope.exp = selector;
		});
	};

	$scope.ok = function () {
		//use filter to generate abstraction on the result
		var newIns = $filter("translateIns")([{
			LINE: -1,
			TYPE: 2,
			BODY: {
				exp: $scope.exp,
				timeout: parseInt($scope.timeout),
				key: $scope.key
			}
		}])[0];

		if (data.edit) {
			data.ins[data.index] = newIns;
		} else {
			if (data.index > -1) {
				data.ins.splice(data.index, 0, newIns);
			}
			//nothing is selected, append instruction at the end
			else {
				data.ins.push(newIns);
			}
		}
		///have to manually refresh
		data.refresh();

		DI.closeDialog();
	};
});